package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Comment;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//import org.apache.log4j.Logger;

import util.KeyGen;
import util.ParameterCheck;
import dao.CommentDao;

/**
 * Servlet implementation class GetComments
 */
public class GetComments extends HttpServlet {
	private static final long serialVersionUID = 1L;
//	private static Logger log = Logger.getLogger(GetComments.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetComments() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String msg = "";
		String result = "";

		String iid = request.getParameter("itemid");
		String page = request.getParameter("page");

		if (ParameterCheck.isEmpty(iid)) {
			msg = "-1";
		} else {

			int itemid = KeyGen.convertCode2Id(iid);
			int pageNo = 0;
			if (!ParameterCheck.isEmpty(page)) {
				pageNo = Integer.parseInt(page);
			}
			
			List<Comment> comlist = new CommentDao().getComments(itemid, pageNo);
			msg =String.valueOf( new CommentDao().getCommentCount(itemid));
			result = JSONArray.fromObject(comlist).toString();

		}
//		log.info(msg);
//		log.info(result);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", msg);
		jsonObject.put("res", result);

		out.print(jsonObject.toString());

		out.flush();
		out.close();
	}
}
